//
//  MJDIYHeader.m
//  MJRefreshExample
//
//  Created by MJ Lee on 15/6/13.
//  Copyright © 2015年 小码哥. All rights reserved.
//

#import "MJDIYHeader.h"
#import "DGActivityIndicatorView.h"

#define kNormalPullingOffsetY -60.0f
API_AVAILABLE(ios(10.0))
@interface MJDIYHeader()
@property (nonatomic,strong) XHomeDropView*dropView;
@property (nonatomic,strong) DGActivityIndicatorView*activityIndicatorView;
@property (nonatomic,strong) UIImpactFeedbackGenerator*feedbackGenerator;
@property (assign, nonatomic) CGFloat insetTDelta;
@property (assign, nonatomic) BOOL needFeedback;
@property (assign, nonatomic) BOOL dropOpen;

@end

@implementation MJDIYHeader
#pragma mark - 重写方法
#pragma mark 在这里做一些初始化配置（比如添加子控件）
- (void)prepare
{
    [super prepare];
    self.backgroundColor = UIColor.blackColor;
    // 设置控件的高度
    self.mj_h = 50.f;
    self.dropView = [[XHomeDropView alloc]initWithFrame:CGRectZero];
    [self addSubview:self.dropView];
    kWeakSelf(self);
    self.dropView.HeaderSectionBlock = ^(XDAPP_RecentlyType type) {
        !weakself.HeaderSectionBlock?:weakself.HeaderSectionBlock(type);
    };
    self.activityIndicatorView = [[DGActivityIndicatorView alloc]initWithType:DGActivityIndicatorAnimationTypeThreeDots tintColor:UIColor.whiteColor];
    [self addSubview:self.activityIndicatorView];
    [self.dropView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.size.equalTo(self);
        make.top.equalTo(self.mas_top).offset(kNormalPullingOffsetY);
    }];
    [self.activityIndicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(AdaptedWidth(5.0f), AdaptedWidth(5.0f)));
        make.centerX.equalTo(self);
        make.bottom.mas_equalTo(-AdaptedWidth(20.0f));
    }];
    [self.activityIndicatorView stopAnimating];
    
    if (@available(iOS 10.0, *)) {
        self.feedbackGenerator = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleLight];
        [self.feedbackGenerator prepare];
    } else {
        // Fallback on earlier versions
    }
    
    self.dropView.clickItemBlock = ^(FoundRecommendModel * _Nonnull model) {
        !weakself.clickItemBlock?:weakself.clickItemBlock(model);
    };
//    self.automaticallyChangeAlpha = YES;
}

#pragma mark 在这里设置子控件的位置和尺寸
- (void)placeSubviews
{
    [super placeSubviews];
}

#pragma mark 监听scrollView的contentOffset改变

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-missing-super-calls"
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
{
    
//    [super scrollViewContentOffsetDidChange:change];
    // 在刷新的refreshing状态
    if (self.state == MJRefreshStateRefreshing) {
        // 暂时保留
        if (self.window == nil) return;
        // sectionheader停留解决
        CGFloat insetT = - self.scrollView.mj_offsetY > _scrollViewOriginalInset.top ? - self.scrollView.mj_offsetY : _scrollViewOriginalInset.top;
        insetT = insetT > self.mj_h + _scrollViewOriginalInset.top ? self.mj_h + _scrollViewOriginalInset.top : insetT;
        self.scrollView.mj_insetT = insetT;
        
        self.insetTDelta = _scrollViewOriginalInset.top - insetT;
        return;
    }
    
    // 跳转到下一个控制器时，contentInset可能会变
    _scrollViewOriginalInset = self.scrollView.mj_inset;
    
    // 当前的contentOffset
    CGFloat offsetY = self.scrollView.mj_offsetY;
    // 头部控件刚好出现的offsetY
    CGFloat happenOffsetY = - self.scrollViewOriginalInset.top;
    
    // 如果是向上滚动到看不见头部控件，直接返回
    // >= -> >
    if (offsetY > happenOffsetY) return;
    if (offsetY >= kNormalPullingOffsetY) {
        CGFloat pullingPercent = offsetY / kNormalPullingOffsetY;
        self.activityIndicatorView.alpha = pullingPercent;
        if (pullingPercent<=0.0) {
            self.activityIndicatorView.transform = CGAffineTransformIdentity;
        }else{
            self.activityIndicatorView.transform = CGAffineTransformMakeScale(pullingPercent,pullingPercent);
        }
    }
    // 普通 和 即将刷新 的临界点
//    CGFloat normal2pullingOffsetY = happenOffsetY - self.mj_h;
    CGFloat pullingPercent = (happenOffsetY - offsetY) / self.mj_h;
    if (self.scrollView.isDragging) { // 如果正在拖拽
        self.pullingPercent = pullingPercent;
        if (self.state == MJRefreshStateIdle && offsetY < kNormalPullingOffsetY) {
            // 转为即将刷新状态
            self.state = MJRefreshStatePulling;
           
        } else if (self.state == MJRefreshStatePulling && offsetY >= kNormalPullingOffsetY) {
            // 转为普通状态
            self.state = MJRefreshStateIdle;
        }
    } else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开
        // 开始刷新
        [self beginRefreshing];
    } else if (pullingPercent < 1) {
        self.pullingPercent = pullingPercent;
    }
}
#pragma clang diagnostic pop

#pragma mark 监听scrollView的contentSize改变
- (void)scrollViewContentSizeDidChange:(NSDictionary *)change
{
    [super scrollViewContentSizeDidChange:change];
}

#pragma mark 监听scrollView的拖拽状态改变
- (void)scrollViewPanStateDidChange:(NSDictionary *)change
{
    [super scrollViewPanStateDidChange:change];
    if ([change[@"new"] integerValue]==3) {
        DLog(@"停止拖拽");
        if (_dropOpen) {
            CGFloat offsetY = self.scrollView.mj_offsetY;
            if (offsetY-8.0f > -self.mj_h) {
                [self endRefreshing];
                [UIView animateWithDuration:0.35f animations:^{
                    [self.dropView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.mas_equalTo(kNormalPullingOffsetY);
                    }];
                }];
                _dropOpen = NO;
            }
        }
    }
}

#pragma mark 监听控件的刷新状态
- (void)setState:(MJRefreshState)state
{
    MJRefreshCheckState;

    switch (state) {
        case MJRefreshStateIdle:{
            _needFeedback = NO;
            if (_dropOpen) {
                CGFloat offsetY = self.scrollView.mj_offsetY;
                if (offsetY-8.0f > -self.mj_h) {
                    [self endRefreshing];
                    [UIView animateWithDuration:0.35f animations:^{
                        [self.dropView mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.top.mas_equalTo(kNormalPullingOffsetY);
                        }];
                    }];
                    _dropOpen = NO;
                }
            }
            [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            [self.activityIndicatorView stopAnimating];
            }
            break;
        case MJRefreshStatePulling:{
            if (!_needFeedback) {
                DLog(@"震动");
                if (@available(iOS 10.0, *)) {
                    [self.feedbackGenerator impactOccurred];
                }
                _needFeedback = YES;
                _dropOpen = NO;
            }
            [self.activityIndicatorView startAnimating];
        }
            break;
        case MJRefreshStateRefreshing:{
            _needFeedback = NO;
            _dropOpen = YES;
            self.activityIndicatorView.alpha = 0.0f;
            [self.activityIndicatorView stopAnimating];
                [UIView animateWithDuration:0.35f animations:^{
                    [self.dropView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.mas_equalTo(0);
                    }];
                }];
            }
            break;
        default:
            break;
    }
}

- (void)dropShow{
    
}
#pragma mark 监听拖拽比例（控件被拖出来的比例）
- (void)setPullingPercent:(CGFloat)pullingPercent
{
    [super setPullingPercent:pullingPercent];
}

- (void)setCollectionArr:(NSArray<FoundRecommendModel *> *)collectionArr{
    _collectionArr = collectionArr;
    self.dropView.collectionArr = collectionArr;
}
- (void)setRecentlyUseArr:(NSArray<FoundRecommendModel *> *)recentlyUseArr{
    _recentlyUseArr = recentlyUseArr;
    self.dropView.recentlyUseArr = recentlyUseArr;
}
@end
